package com.ruoyi.system.controller;

import com.ruoyi.common.core.constant.SecurityConstants;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.system.api.RemoteUserService;
import com.ruoyi.system.api.model.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.scheduling.annotation.Async;
import org.springframework.web.bind.annotation.*;
import org.springframework.http.HttpStatus;

import java.util.Random;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/email")
public class SysEmailController extends BaseController {

    @Autowired
    private JavaMailSender javaMailSender;

    @Autowired
    private RemoteUserService remoteUserService;

    @Autowired
    private StringRedisTemplate redisTemplate;  // Redis模板

    // Redis中的验证码存储前缀
    private static final String VERIFICATION_CODE_PREFIX = "email:verification_code:";

    @Async
    @GetMapping("/send")
    public void sendEmail() {
        // 创建邮件消息
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom("3397174734@qq.com");   // 发件人地址

        // 获取当前登录用户信息
        R<LoginUser> loginUserR = remoteUserService.getUserInfo(SecurityUtils.getUsername(), SecurityConstants.FROM_SOURCE);
        LoginUser loginUser = loginUserR.getData();
        //message.setTo("2338713074@qq.com");
        message.setTo(loginUser.getSysUser().getEmail());                         // 收件人地址
        message.setSubject("验证码");               // 邮件主题
        String uuid = generateCode();

        // 设置邮件内容
        message.setText("验证码为：" + uuid);

        // 发送邮件
        javaMailSender.send(message);

        // 将验证码存入 Redis 中，并设置过期时间（如 5 分钟）
        //storeVerificationCodeInRedis("2338713074@qq.com", uuid);
        storeVerificationCodeInRedis(loginUser.getSysUser().getEmail(), uuid);
    }

    // 生成6位随机验证码
    public static String generateCode() {
        int length = 6;
        String charSet = "0123456789";
        Random random = new Random();
        StringBuilder code = new StringBuilder();
        for (int i = 0; i < length; i++) {
            int index = random.nextInt(charSet.length());
            code.append(charSet.charAt(index));
        }
        return code.toString();
    }

    // 将验证码存储在 Redis 中
    private void storeVerificationCodeInRedis(String email, String code) {
        // 获取 Redis 的 ValueOperations 对象
        ValueOperations<String, String> ops = redisTemplate.opsForValue();

        // 将验证码存入 Redis，设置有效期为 5 分钟（300 秒）
        ops.set(VERIFICATION_CODE_PREFIX + email, code, 5, TimeUnit.MINUTES);
    }

    // 验证用户输入的验证码
    @PostMapping("/{verify}")
    public Boolean verifyCode(@PathVariable("verify") String inputCode) {
        R<LoginUser> loginUserR = remoteUserService.getUserInfo(SecurityUtils.getUsername(), SecurityConstants.FROM_SOURCE);
        LoginUser loginUser = loginUserR.getData();
        String email =  loginUser.getSysUser().getEmail();
        // 获取 Redis 中存储的验证码
        ValueOperations<String, String> ops = redisTemplate.opsForValue();
        String redisCode = ops.get(VERIFICATION_CODE_PREFIX + email);

        // 如果 Redis 中没有找到验证码或者验证码不匹配
        if (redisCode == null) {
            return null;
        }

        // 校验用户输入的验证码是否与 Redis 中的验证码一致
        if (redisCode.equals(inputCode)) {
            return true;
        } else {
            return false;
        }
    }
}
